package com.uni.crawl.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.uni.crawl.common.enums.crawl.CrawlQueueStatusEnum;
import com.uni.crawl.model.entity.crawl.CrawlQueue;
import com.uni.crawl.service.crawl.CrawlDataService;
import com.uni.crawl.service.crawl.CrawlInstanceService;
import com.uni.crawl.service.crawl.CrawlQueueService;
import com.uni.crawl.service.crawl.CrawlTemplateService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
@AllArgsConstructor
public class CrawlQueueConsumerJob extends AbstractJob {

    protected final CrawlTemplateService crawlTemplateService;
    private final CrawlInstanceService crawlInstanceService;
    private final CrawlQueueService crawlQueueService;
    private final CrawlDataService crawlDataService;
    private final RestTemplate restTemplate;

    @XxlJob("crawlQueueConsumerJob")
    @Override
    public ReturnT<String> handle() {
        LambdaQueryWrapper<CrawlQueue> wp = Wrappers.lambdaQuery();
        wp.eq(CrawlQueue::getCrawlStatus, CrawlQueueStatusEnum.INIT.getStatus());

        List<CrawlQueue> dequeueList = crawlQueueService.list(wp);
        log.info("need dequeue size = {}", dequeueList.size());
        for (CrawlQueue queue : dequeueList) {
            try {
                crawlQueueService.setQueueStatus(queue.getId(), CrawlQueueStatusEnum.PROCESSING);

                ResponseEntity<String> httpResponse = restTemplate.getForEntity(queue.getUrl(), String.class);
                queue.setHttpStatus(httpResponse.getStatusCode().value());
                queue.setHttpResponse(httpResponse.getBody());

            } catch (Exception e) {
                log.error("处理失败", e);
                queue.setCrawlStatus(CrawlQueueStatusEnum.ERR.getStatus());
            }

            queue.setCrawlStatus(CrawlQueueStatusEnum.FINISH.getStatus());
            queue.setUpdateTime(LocalDateTime.now());
            crawlQueueService.updateById(queue);
            crawlInstanceService.increaseFinish(queue.getInstanceId(), 1);
        }


        return success();
    }
}
